package com.ftdigital.primemovers_operators.fragment;


import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;

import com.ftdigital.primemovers_operators.MyApplication;
import com.ftdigital.primemovers_operators.config.Config;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.model.BaseModel;
import com.ftdigital.primemovers_operators.model.Entity;
import com.ftdigital.primemovers_operators.util.CacheManager;
import com.ftdigital.primemovers_operators.util.XTHttp;
import com.google.gson.Gson;

import java.io.Serializable;
import java.lang.ref.WeakReference;

/**
 * CoreFragment.
 */
public class CoreFragment<T  extends Entity> extends Fragment implements BaseInterface {

    static Gson gson = new Gson();
    static XTHttp xtHttp = new XTHttp();
    BaseModel baseModel;

    protected int currentPage = 0;

    protected static String requestUrl = "";//访问地址
    protected static String requestParams = "";//访问参数

    private AsyncTask<String, Void, Object> readCacheTask;
    private ParaserTask paraserTask;


    @Override
    public void initView() {

    }

    @Override
    public void Click(View view) {

    }

    //请求数据
    @Override
    public void requestData() {
    }

    //执行 其网络请求成功后
    @Override
    public void executeOnSuccess(Object object) {

    }

    @Override
    public String getCachePrifix() {
        return null;
    }

    //将从缓存中获取的数据 读取为Bean
    protected Object readList(Serializable serializable) {
        return null;
    }

    protected String getCache() {
        return new StringBuilder(getCachePrifix()).append("_").append(currentPage).toString();
    }

    //jsonobject 转 Bean
    protected T parseList(Object object) {
        return null;
    }

    @Override
    public void loadData() {
        //是否手动刷新
        if (isReadCacheData()) {
            readCache();
//            Log.i(GlobalData.TAG, "readCache");
        } else {
//            Log.i(GlobalData.TAG, "requestData");
            requestData();
        }
    }

    // 1、缓存存在且有效
    // 2、沒有網絡
    private boolean isReadCacheData() {
//        Log.i(GlobalData.TAG, "isFileExist：" + CacheManager.isFileExist(getActivity(), getCache()));
//        Log.i(GlobalData.TAG, "isCacheDataFaile：" + !CacheManager.isCacheDataFaile(getActivity(), getCache()));
        if (CacheManager.isFileExist(getActivity(), getCache())
                && !CacheManager.isCacheDataFaile(getActivity(), getCache())) {
            return true;
        }
        return false;
    }

    //开启读异步线程
    protected void readCache() {
        cancleCacheTask();
        readCacheTask = new ReadCacheTask(getActivity()).execute(getCache());
    }

    //取消运行线程，开启新线程
    private void cancleCacheTask() {
        if (readCacheTask != null) {
            readCacheTask.cancel(true);
            readCacheTask = null;
        }
    }

    //读取缓存
    private class ReadCacheTask extends AsyncTask<String, Void, Object> {

        private WeakReference<Context> context;

        public ReadCacheTask(Context context) {
            this.context = new WeakReference<Context>(context);
        }

        @Override
        protected Object doInBackground(String... strings) {
            Serializable serializable = CacheManager.readObject(context.get(), strings[0]);
//            Log.i(GlobalData.TAG, "readObject ser:" + serializable);
            if (serializable == null) {
                return null;
            } else {
                //处理list
                return readList(serializable);
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o != null) {
                //开始赋值
//                executeOnSuccess(o);
                Log.i(GlobalData.TAG, "onPostExecute");
                executeParserTask(o);
            } else {
                //执行失败后的操作
            }
        }
    }


    //执行转换任务
    protected void executeParserTask(Object object) {
//        Log.i(GlobalData.TAG, "executeParserTask");
        cancleParserTask();
        paraserTask = new ParaserTask(getActivity(), object);
//        Log.i(GlobalData.TAG, "execute");
        paraserTask.execute();
    }

    //取消正在执行转换任务
    private void cancleParserTask() {
        if (paraserTask != null) {
            paraserTask.cancel(true);
        }
    }

    //
    class ParaserTask extends AsyncTask<Void, Void, Boolean> {

        private Object object;
        private T t;
        private Context context;

        public ParaserTask(Context context, Object object) {
            this.context = context;
            this.object = object;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            boolean parserError = false;
            t = parseList(object);
//            Log.i(GlobalData.TAG, "ParaserTask doInBackground");
            //开始保存缓存
            new SaveCacheTask(context, object, getCache()).execute();
            if (t == null)
                parserError = true;
            else{
                parserError = false;
            }
            return parserError;
        }

        @Override
        protected void onPostExecute(Boolean parserError) {
            super.onPostExecute(parserError);
            if (parserError) {
                readCache();
            } else {
                //赋值
                executeOnLoadData(t);
            }
        }
    }

    //加载数据处理界面
    protected void executeOnLoadData(T t) {
        // 是否有错误信息
        // 设置Errorlayout的状态， 如为空，无网络等
        // 如果为首页则清理adapter数据
        // 检查获取数据中与现有数据重复数据 删除
        // 如果获取的数据size 为零
        // 如果size小于页面大小
        // 添加数据
    }

    class SaveCacheTask extends AsyncTask<Void, Void, Void> {

        private Serializable serializable;
        private String cachefile;
        private Context context;

        public SaveCacheTask(Context context, Object data, String cachefile) {
            this.context = context;
            this.serializable = data.toString();
            this.cachefile = cachefile;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            CacheManager.saveObject(context, serializable, cachefile);
            return null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (onTimeRefreash()){
            requestData();
        }
    }

    //自动刷新时间
    private boolean onTimeRefreash() {
        long lastRefreashTime = MyApplication.getRefreashTime(getCache());
        long diff = lastRefreashTime - System.currentTimeMillis();
        return needAutoRefreash() && diff > Config.AUTO_REFREASH_TIMR;
    }

    private boolean needAutoRefreash() {
        return true;
    }
}
